<template>
  <div>
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="baseJsObj.breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      :state="state"
      @handleBack="handleBack"
    />
    <div class="ccui-app-container-detail" v-if="isTrue">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <!--  基本信息  -->
          <el-tab-pane label="基本信息" name="first">
            <detailBaseInfo
              ref="basicInfo"
              labelWidth="130px"
              :formList="baseFormList"
              :detail="basicInfo"
            />
          </el-tab-pane>
          <!--  财务信息  -->
          <el-tab-pane label="财务信息" name="second">
            <financeInfo ref="financial" :detail="financial" />
            <!-- <detailBaseInfo
              ref="financeInfo"
              labelWidth="130px"
              :formList="baseJsObj.financeFormList"
              :detail="financial || {}"
            /> -->
          </el-tab-pane>
          <!-- 采购清单 -->
          <el-tab-pane label="采购清单" name="third">
            <oneLineTable
              ref="purchaseList"
              showSummary
              :summaryArr="summaryArr"
              :tableTheadOptions="
                this.state === 'create'
                  ? baseJsObj.purchaseTableThead1
                  : baseJsObj.purchaseTableThead
              "
              :oneLineTableData="purchaseList"
            />
          </el-tab-pane>
          <!-- 使用范围 -->
          <el-tab-pane label="使用范围" name="fourth">
            <oneLineTable
              ref="usingRange"
              :tableTheadOptions="baseJsObj.useRangeTableThead"
              :oneLineTableData="usingRange"
            />
          </el-tab-pane>
          <!-- 付款方式 -->
          <el-tab-pane label="付款方式" name="fifth">
            <paymentMode :detail="componentsDatil"></paymentMode>
          </el-tab-pane>
          <!-- 合同附件 -->
          <el-tab-pane label="合同附件" name="sixth">
            <contractAnnex
              ref="contractAnnex"
              isTab
              v-model="attachmentDownload"
              state="detail"
            />
          </el-tab-pane>
          <!-- 协议信息 -->
          <el-tab-pane label="补充协议" name="seventh">
            <agreementInfo :agreementInfo="agreementInfo" ref="agreementInfo" />
          </el-tab-pane>
          <!-- 协议历史 -->
          <el-tab-pane label="协议历史" name="eighth">
            <oneLineTable
              :highlightNodeArr="['protocolCode']"
              ref="histryAgreement"
              :tableTheadOptions="baseJsObj.histryAgreementTableThead"
              :oneLineTableData="histryAgreement"
              @gotoDetail="goAgreementHistory"
            />
          </el-tab-pane>
          <!-- 变更历史 -->
          <el-tab-pane label="变更历史" name="ninth">
            <oneLineTable
              :highlightNodeArr="['contractCode']"
              ref="histryChanges"
              :tableTheadOptions="baseJsObj.histryChangesTableThead"
              :oneLineTableData="histryChanges"
              @gotoDetail="goContractHistory"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(0)"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(1)"
            >保存并提交</el-button
          >
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import baseJsObj from "../js";
// import publicComponent from "@/basa/components/public";
import breadcrumb from "./breadcrumb.vue";
import detailBaseInfo from "./detailBaseInfo.vue";
import oneLineTable from "./oneLineTable.vue";
import contractAnnex from "./uploadInfo.vue";

// import contractComponent from "@/app/contractManagement/components";
import financeInfo from "../detail/financeInfo.vue";
import paymentMode from "../detail/paymentMode.vue";
import agreementInfo from "../detail/agreementInfo.vue";
import {
  getEquipmentProtocolConcDetail,
  getAgreementAdd,
  getAgreementEditor
} from "../api";
import { proxyDateFormat } from "@/basa/utils";
export default {
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    // financeInfo: contractComponent.detailFinanceInfo,
    // paymentMode: contractComponent.detailPaymentMode,
    // agreementInfo: contractComponent.agreementInfo,
    financeInfo,
    paymentMode,
    agreementInfo,
    breadcrumb,
    detailBaseInfo,
    oneLineTable,
    contractAnnex
    // breadcrumb: publicComponent.breadcrumb,
    // detailBaseInfo: publicComponent.detailBaseInfo,
    // oneLineTable: publicComponent.oneLineTable,
    // contractAnnex: publicComponent.uploadInfo
  },
  data() {
    return {
      baseJsObj,
      breadcrumbLastItem: "合同补充协议",
      isTrue: false,
      baseFormList: [],
      financial: [],
      purchaseList: [],
      usingRange: [],
      paymentMode: [],
      componentsDatil: [],
      attachmentDownload: [],
      attachmentUpload: [],
      agreementInfo: {},
      histryAgreement: [],
      histryChanges: [],
      focus: "basicInfo",
      activeName: "first",
      basicInfo: {}, //基本信息
      concId: "", //合同id
      summaryArr: [
        "currentNum",
        "currentChangeAmtExcludeTax",
        "currentChangeAmtIncludeTax",
        "rate"
      ]
    };
  },
  activated() {
    this.getDetail();
  },
  methods: {
    // 详情
    getDetail() {
      this.concId = this.$route.query.concId;
      let protocolId = this.$route.query.protocolId
        ? this.$route.query.protocolId
        : "";
      let data = {
        concId: this.concId,
        proConId: protocolId,
        isShowWorkflow: "0",
        isShowPageLoading: true
      };
      getEquipmentProtocolConcDetail(data).then(res => {
        if (res.data.code == 0) {
          const data = res.data.data;
          this.componentsDatil = res.data.data;
          const jsFormList = cloneDeep(baseJsObj.baseFormList);
          // 币种判断
          if (data.smpPcConc.currencyName === "人民币") {
            const i = jsFormList.findIndex(
              _ => _.titleContent === "chExchangeRate"
            );
            jsFormList.splice(i, 1);
            const j = jsFormList.findIndex(
              _ => _.titleContent === "exchangeRateRefDate"
            );
            jsFormList.splice(j, 1);
          }
          // 兑美元美元汇率
          if (
            data.smpPcConc.isOverseas !== 3 &&
            !["人民币", "美元"].includes(data.smpPcConc.currencyName)
          ) {
            const i = jsFormList.findIndex(
              _ => _.titleContent === "compileUser"
            );
            jsFormList.splice(i, 0, {
              label: "兑美元汇率",
              titleContent: "usExchangeRate"
            });
          }
          // 多税率判断
          if (data.smpPcConc.multiRateCode === 0) {
            const i = jsFormList.findIndex(
              _ => _.titleContent === "taxRatePercent"
            );
            jsFormList.splice(i, 1);
          }

          // 是否浮动合同价格判断
          if (data.smpPcConc.isFloatContractPrice === 1) {
            const i = jsFormList.findIndex(_ => _.titleContent === "floatDesc");
            jsFormList.splice(i, 1);
          }
          this.baseFormList = jsFormList;
          data.smpPcConc = {
            ...data.smpPcConc,
            compileDateStr:
              data.smpPcConc.compileDate !== null
                ? data.smpPcConc.compileDate.substring(0, 10)
                : "",
            exchangeRateRefDate:
              data.smpPcConc.exchangeRateRefDate !== null
                ? data.smpPcConc.exchangeRateRefDate.substring(0, 10)
                : "",
            // 是否浮动合同价格
            isFloatContractPrice: baseJsObj.whetherList.find(
              _ => _.dicKey === data.smpPcConc.isFloatContractPrice
            ).dicValue,
            // 是否海外采购
            isOverseas: baseJsObj.isOverseasList.find(
              _ => _.value === data.smpPcConc.isOverseas
            ).label,
            // 多税率
            multiRateCode:
              data.smpPcConc.multiRateCode !== null
                ? baseJsObj.whetherList.find(
                    _ => _.dicKey === data.smpPcConc.multiRateCode
                  ).dicValue
                : ""
          };
          this.basicInfo = data.smpPcConc;
          this.titleName = data.smpPcConc.contractName;
          this.financial = data.pcFinance;
          this.basicInfo.contractPerson =
            this.financial.length && this.financial[0].contractPerson;
          this.basicInfo.contractPersonTel =
            this.financial.length && this.financial[0].contractPersonTel;
          this.purchaseList = res.data.data.smpConcMatLessList;
          this.purchaseList.forEach(item => {
            item.currentNum = Number(item.currentNum).toFixed(3);
            item.currentChangeAmtExcludeTax = Number(
              item.currentChangeAmtExcludeTax
            ).toFixed(2);
            item.currentUnitPriceExcludeTax = Number(
              item.currentUnitPriceExcludeTax
            ).toFixed(2);
            item.currentUnitPriceIncludeTax = Number(
              item.currentUnitPriceIncludeTax
            ).toFixed(2);
            item.currentChangeAmtIncludeTax = Number(
              item.currentChangeAmtIncludeTax
            ).toFixed(2);
            item.rate = Number(item.rate).toFixed(2);
            item.PlaceDelivery =
              item.deliveryAreaName +
              item.provinceName +
              item.cityName +
              item.countyName +
              item.deliveryPoints;
          });
          this.usingRange = res.data.data.smpUsableRange.map(n => ({
            ...n,
            operationTimeStr:
              n.operationTime !== null ? proxyDateFormat(n.operationTime) : ""
          }));
          this.paymentMode = res.data.data.payTypeListBOS;
          this.attachmentDownload = res.data.data.concFiles;
          this.histryChanges = res.data.data.oldSmpPcConcList.map(n => ({
            ...n,
            compileDateStr:
              n.compileDate !== null ? proxyDateFormat(n.compileDate) : ""
          }));
          this.histryAgreement = res.data.data.smpProtocolList;

          this.agreementInfo = {
            state: this.state,
            smpProtocol: res.data.data.smpProtocol,
            protocolConcFiles: res.data.data.protocolConcFiles
          };

          this.isTrue = true;
        }
      });
    },
    // 新增/编辑
    async submitHandle(operType) {
      try {
        let {
          smpProtocolBO,
          fileReqBOS
        } = await this.$refs.agreementInfo.handleSubmit();

        if (this.state === "create") {
          smpProtocolBO = { ...smpProtocolBO, concId: this.concId };
        }

        let data = {
          smpProtocolBO,
          fileReqBOS,
          operType
        };

        (this.state == "create" ? getAgreementAdd : getAgreementEditor)(
          data
        ).then(res => {
          const { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
            this.handleBack();
          }
        });
      } catch (error) {
        this.activeName = error;
        if (["seventh"].includes(error)) {
          this.$nextTick(() => {
            const errorFormEl = document.body.querySelector(".is-error");
            const errorText = errorFormEl.firstChild.innerText;
            const messageText = errorText.substring(
              0,
              errorText.lastIndexOf("：")
            );
            this.$showErrorMessage(`${messageText}未填写，请编辑后保存`);
            if (errorFormEl) {
              errorFormEl.scrollIntoView({
                behavior: "smooth", // 平滑过渡
                block: "start" // 上边框与视窗顶部平齐。默认值
              });
            }
          });
        }
      }
    },

    // 协议历史
    goAgreementHistory({ id, concId }) {
      this.$router.push({
        path: `/contractManagement/materialRentContractAgreement/item-detail`,
        query: {
          concId,
          protocolId: id,
          type: "account"
        }
      });
    },

    // 变更历史
    goContractHistory({ id, protocolId }) {
      this.$router.push({
        path: `/contractManagement/materialRentContractAgreement/item-detail`,
        query: { concId: id, protocolId, type: "account" }
      });
    },

    //返回
    handleBack() {
      this.$router.go(-1);
    }
  },
  deactivated() {
    this.activeName = "first";
    this.isTrue = false;
  }
};
</script>

<style scoped lang="scss"></style>
